package com.jxb.netty;

import com.jxb.RemotingService;
import io.netty.channel.Channel;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class RemotingClient implements RemotingService {

    public ConcurrentMap<String /* addr */, ChannelWrapper> channelTables = new ConcurrentHashMap<String, ChannelWrapper>();

    @Override
    public void sendOneway(RemotingCommand request) {
        channelTables.forEach((k,v)->{
            Channel channel = v.getChannelFuture().channel();
            if (channel != null && channel.isActive()) {
                channel.writeAndFlush(request);
//                channel.closeFuture();
//                channelTables.remove(k);
            }
        });
    }

    @Override
    public void contectNamesrvs(String[] namesrvAddrs, String clientName) {
        for (String namesrvAddr : namesrvAddrs) {
            String[] split = namesrvAddr.split(":");
            String ip = split[0];
            int port = Integer.parseInt(split[1]);
            try {
                NettyRemotingClient client = new NettyRemotingClient(ip, port, clientName);
                client.start();
                ChannelWrapper channelWrapper = client.channelWrapper;
                channelTables.put(namesrvAddr,channelWrapper);
            }catch (Exception e) {

            }
        }
    }

    @Override
    public void sendMessage(String s, int i, String hahaha) {
        SendMessageRequestHeader requestHeader = new SendMessageRequestHeader();
        requestHeader.setProducerGroup("testGroup");
        requestHeader.setTopic("testTopic");
        requestHeader.setDefaultTopic("defaultTopic");
        requestHeader.setDefaultTopicQueueNums(2);
        requestHeader.setQueueId(1);
        requestHeader.setSysFlag(1);
        requestHeader.setBornTimestamp(System.currentTimeMillis());
        requestHeader.setFlag(1);
        requestHeader.setProperties("properties");
        requestHeader.setReconsumeTimes(0);
        requestHeader.setUnitMode(false);
        requestHeader.setBatch(false);
        requestHeader.setReconsumeTimes(1);
        requestHeader.setMaxReconsumeTimes(1);
        RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, requestHeader);
        request.setBody(hahaha.getBytes(StandardCharsets.UTF_8));
        ChannelWrapper channelWrapper = channelTables.get(s + i);
        channelWrapper.getChannelFuture().channel().writeAndFlush(request);
    }

    @Override
    public void contectBroker(String ip, int host, String clientName) {
        NettyRemotingClient client = new NettyRemotingClient(ip, host, clientName);
        try {
            client.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ChannelWrapper channelWrapper = client.channelWrapper;
        channelTables.put(ip+host,channelWrapper);
    }

}
